<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <h2 class="setting-header">
        <strong>公告管理</strong>
      </h2>
      <div class="top-btns">
        <el-button class="add-button" type="primary" @click="createNotice"
          >新增公告</el-button
        >
        <SearchCmp
          v-if="searchCmpArray.length"
          :searchCmpArray="searchCmpArray"
          :searchForm="queryData"
          @onSubmit="getTableData"
        />
      </div>
      <RuifoxTable
        v-loading="tableLoading"
        :table-data="tableData"
        :field-list="fieldList"
        :default-index="true"
        :default-checkbox="true"
        :lazy="true"
      >
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox
              class="unmover"
              v-model="element.checked"
              @change="handleCheckTable(element.id)"
              size=""
            />
          </div>
        </template>

        <template #title="{ element }" >
          <div class="notice-title">{{element.title}}</div>
        </template>

        <!-- 公告目标显示 -->
        <template #targetId="{ element }" >
          <div v-if="element?.targetInfo?.departName">{{element.targetInfo.departName}}</div>
          <div v-else-if="element?.targetInfo?.courseName">{{element.targetInfo.courseName}}-{{element.targetInfo.courseInstanceName}}</div>
          <div v-else>系统</div>
        </template>

        <!-- 课程类型列 -->
        <template #type="{ element }" >
          <el-tag v-if="element.type == 'SYSTEM'" type="primary">系统</el-tag>
          <el-tag v-if="element.type == 'COURSE_INSTANCE'" type="success">课程</el-tag>
          <el-tag v-if="element.type == 'DEPARTMENT'" type="success">部门</el-tag>
        </template>

        <!-- 置顶  -->
        <template #top="{ element }">
          <el-tag v-if="element.top == true" type="success">是</el-tag>
          <el-tag v-if="element.top == false" type="info">否</el-tag>
        </template>

        <!-- 创建时间  -->
        <template #createdAt="{ element }">
          <div class="item-info">{{ formatDate(element.createdAt,"yyyy-MM-dd hh:mm") }}</div>
        </template>

        <!-- 更新时间  -->
        <template #updatedAt="{ element }">
          <div class="item-info">{{ formatDate(element.updatedAt,"yyyy-MM-dd hh:mm") }}</div>
        </template>
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button
              type="primary"
              link
              @click="editNotice(element)"
            >
              编辑内容
            </el-button>
            
            <el-button
              type="primary"
              link
              @click="delNotice(element)"
            >
              删除
            </el-button>
          </div>
        </template>
      
      </RuifoxTable>
      <!-- 分页器 -->
      <PaginationView
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="queryData.total > 0"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="getTableData"
        @cancelChoose="handleResetPagination"
      />
    </el-scrollbar>

    <!-- 添加 编辑公告  -->
    <el-drawer
      v-model="dialogVisible"
      :title="dialogTitle"
      size="800px"
      direction="ltr"
      :before-close="handleClosedrawer"
    >
      <el-form
        ref="formRef"
        :model="addNoticeForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addNoticeForm.title" placeholder="请输入公告标题"/>
        </el-form-item>
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="addNoticeForm.type" placeholder="请选择公告类型" style="width: 240px">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="info-row">
          <el-form-item label="选择课程" prop="courseId" v-if="addNoticeForm.type == 'COURSE_INSTANCE'">
            <el-select
              v-model="addNoticeForm.courseId"
              filterable
              placeholder="请选择课程"
              style="width: 240px"
            >
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择期数" prop="targetId" v-if="addNoticeForm.type == 'COURSE_INSTANCE'">
            <el-select
              v-model="addNoticeForm.targetId"
              filterable
              placeholder="请选择期数"
              style="width: 240px"
            >
              <el-option
                v-for="item in instanceLIst"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="选择部门" prop="targetId" v-if="addNoticeForm.type == 'DEPARTMENT'">
          <el-select
            v-model="addNoticeForm.targetId"
            filterable
            placeholder="请选择部门"
            style="width: 240px"
          >
            <el-option
              v-for="item in departList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶" prop="top">
          <el-switch v-model="addNoticeForm.top" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <TinymceEditor
            v-model:modelValue="addNoticeForm.content"
            :minHeight="400"
          />
        </el-form-item>
      
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmGroup(formRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { 
  pagingAnnouncement,
  createAnnouncement,
  updateByIdAnnouncement,
  deleteByIdsAnnouncement,
} from '@/api/notice'
import { tableList as mixTable } from "@ruifox-cms/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import TinymceEditor from "@/components/TinymceEditor.vue";
import { formatDate } from '@/utils/tools'
import { selectPageCourse } from '@/api/course'
import { selectPageInstance } from '@/api/instance'
import { getDepartTree } from "@/api/depart";

//关闭对话框
// const handleClosedrawer = () => { 
//   ElMessageBox.confirm('是否保存该公告', '提示', {
//     distinguishCancelAndClose: true,
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   }).then(async () => {
//     confirmGroup()
//   }).catch(() => {
//     dialogVisible.value = false;
//   })
// }

//获取课程
const courseForm = ref({
  currentPage: 1,
  pageSize: 10,
  name: "",
  type: "",
  status: "",
  needCheck: "",
  approvalStatus: "",
  createdBy: "",
  updatedBy: ""
})
const courseList = ref([])
const getCourse = async () => {
  const res = await selectPageCourse(courseForm.value)
  if (res.code === 20000) {
    courseList.value = res.data.list
    console.log("courseList.value",courseList.value);
  }
}
const departList = ref([]);
const getDepart = async () => {
  const res = await getDepartTree()
  if (res.code === 20000) {
    departList.value = res.data.children
  }
}

//表格数据
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: pagingAnnouncement,
  batchFuncApi: deleteByIdsAnnouncement,
});

//分页器
const defaultQuery = reactive({
  total: 10,
  currentPage: 1,
  pageSize: 10,
  sort: "",
  order: "",
  checked: true,
  needToSort: true,
  sortArray: [],
  orderArray: [],
  type: "",
  title: "",
  top: "",
  orderByStatement: "",
  statement: ""
});

Object.assign(queryData, defaultQuery);

//筛选条件
const typeList = ref([
  {
    id: 1,
    value: "COURSE_INSTANCE",
    label: "课程"
  },
  {
    id: 2,
    value: "DEPARTMENT",
    label: "部门"
  },
  {
    id: 3,
    value: "SYSTEM",
    label: "系统"
  }
])
const searchCmpArray = ref([
  { label: "公告标题", key: "title" },
  { label: '公告类型', key: 'type', form_type: 'select', options: typeList.value },
]);
// 公告信息编辑
const dialogVisible = ref(false);
const dialogTitle = ref("");
const defaultNoticeFormData = {
  type: "",  //公告类型,可用值:COURSE_INSTANCE(course_instance,课程),DEPARTMENT(department,部门),SYSTEM(system,系统)
  targetId: "",  //公告目标id
  courseId: "",
  title: "",
  content: "",
  top: false,  //是否置顶
  sortOrder: 0  //公告排序
};
const addNoticeForm =  ref({ ...defaultNoticeFormData });

//新增公告
const createNotice = () => {
  addNoticeForm.value = { ...defaultNoticeFormData };
  dialogVisible.value = true;
  dialogTitle.value = "新增公告";
};

//编辑公告
const editNotice = async (item) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑公告";
  addNoticeForm.value = { ...item };
};
const rules = reactive({
  title: [{ required: true, message: '请输入公告名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  targetId: [{ required: true, message: '请选择公告目标', trigger: 'change' }],
})
const formRef = ref()
//保存公告
const confirmGroup = async (formEl) => {
  if (!formEl){
    ElMessage.warning("请填写完整公告内容");
    return
  } 
  await formEl.validate(async (valid) => {
    if (valid) {
     
      if(addNoticeForm.value.type == 'SYSTEM'){
        addNoticeForm.value.targetId = "1";
      } else if(addNoticeForm.value.type == 'COURSE_INSTANCE' && Array.isArray(addNoticeForm.value.targetId)) {
        addNoticeForm.value.targetId = addNoticeForm.value.targetId.join(",");
      }
      if (dialogTitle.value == "新增公告") {
        const res = await createAnnouncement(addNoticeForm.value);
        if (res.code === 20000) {
          ElMessage.success("新增公告成功");
        }
      } else if (dialogTitle.value == "编辑公告") {
        const res = await updateByIdAnnouncement(addNoticeForm.value);
        if (res.code === 20000) {
          ElMessage.success("编辑公告成功");
        }
      }
      dialogVisible.value = false;
      getTableData();
    }
  })
};

//删除公告
const delNotice = async (item) => {
  ElMessageBox.confirm("确定删除该公告吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteByIdsAnnouncement({ ids: item.id });
    if (res.code === 20000) {
      ElMessage.success("删除成功");
      getTableData();
    }
  });
};

// 批量删除
const handleBatchNotice = async () => {
  ElMessageBox.confirm("确定删除选中公告吗？", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let data = {
      ids: checkedList.value.join(','),
    };
    deleteByIdsAnnouncement(data).then((res) => {
      if (res.code === 20000) {
        ElMessage.success("删除成功");
        getTableData();
        isAllChooseBtn.value = false;
        checkedList.value = [];
      }
    });
  });
}
const batchOptions = ref([
  { name: "删除", value: "delNotice", icon: "&#xe74b;" },
]);
const handleBatchOptions = (data) => {
  if (data === "delNotice") {
    handleBatchNotice();
  }  
};

const fieldList = ref([
  {
    title: "标题",
    name: "title",
    width: "200"
  },
  // {
  //   title: "内容",
  //   name: "content",
  // },
  {
    title: "公告类型",
    name: "type",
  },
  {
    title: "公告目标",
    name: "targetId",
  },
  {
    title: "是否置顶",
    name: "top",
  },
  {
    title: "发布时间",
    name: "createdAt",
  },
  {
    title: "更新时间",
    name: "updatedAt",
  },
  {
    title: "操作",
    name: "options",
    width: 200,
    fixed: "right",
  },
]);

onMounted(async() => {
  await getTableData();
  await getCourse();
  await getDepart();
});

//查询课程实例
const instanceForm = ref({
  "currentPage": 1,
  "pageSize": 100,
  courseIds: "",
  "scheduleIds": [],
  "principalIds": [],
  "startTime": "",
  "endTime": "",
  "finish": ""
})
const instanceLIst = ref([])
const getConstance = async () => {
  if (!Array.isArray(instanceForm.value.courseIds)) {
    instanceForm.value.courseIds = [addNoticeForm.value.courseId];
  }
  const res = await selectPageInstance(instanceForm.value)
  if(res.code === 20000){
    instanceLIst.value = res.data.list
  }
}

watch(() => addNoticeForm.value.courseId, async () => {
  addNoticeForm.value.targetId = ""
  await getConstance()
})

</script>

<style scoped lang="scss">
.top-btns{
  display: flex;
  margin-bottom: 20px;
  .add-button{
    margin-right: 20px;
  }
}
.info-row{
  display: flex;
  justify-content: space-between;
  .el-form-item{
    width: 48%;
  }
}
.notice-title{
  font-size: 12px;
  line-height: 18px;
  max-height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-wrap: break-word;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -webkit-box;
}
</style>